const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const safePostCssParser = require("postcss-safe-parser");
const TerserPlugin = require("terser-webpack-plugin");
const SizePlugin = require("size-plugin");
const LoadablePlugin = require('@loadable/webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const isDev = process.env.NODE_ENV === "development";

module.exports = {
    entry: path.join(__dirname, "../client/index.tsx"),
    output: {
        path: path.join(__dirname, "../dist"),
        filename: "static/js/[name].js",
        publicPath: "/",
    },
    module: {
        rules: [
            {
                test: /\.(j|t)s(x)?$/,
                exclude: /node_modules/,
                include: [
                    path.join(__dirname, '../client'),
                    /node_modules\/mobx/,
                    /node_modules\/mobx-react/
                ],
                use: {
                    loader: "babel-loader",
                    options: {
                        cacheDirectory: true,
                    },
                },
            },
            {
                test: /\.(c|le)ss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                        options: {
                            hmr: isDev, // 是开发环境时，开启热更替
                            reloadAll: true, // 当热更替无法正常工作时，重新加载
                        },
                    },
                    {
                        loader: "css-loader",
                    },
                    "postcss-loader",
                    {
                        loader: "less-loader",
                        options: {
                            lessOptions: {
                                javascriptEnabled: true,
                            },
                        },
                    },
                ],
            },
            {
                test: /\.ejs$/,
                use: {
                    loader: 'ejs-compiled-loader',
                    options: {
                        htmlmin: true,
                        htmlminOptions: {
                            removeComments: true
                        }
                    }
                }
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                use: {
                    loader: "url-loader",
                    options: {
                        limit: 1024 * 10,
                        name: "static/img/[name].[hash:7].[ext]",
                    },
                },
            },
            {
                test: /\.(ttf|eot|otf|woff2?)(\?.*)?$/,
                loader: "file-loader",
                options: {
                    name: "static/fonts/[name].[hash:7].[ext]",
                },
            },
        ],
    },
    optimization: {
        minimize: !isDev,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    parse: {
                        ecma: 8,
                    },
                    compress: {
                        ecma: 5,
                        warnings: false,
                        comparisons: false,
                        inline: 2,
                    },
                    mangle: {
                        safari10: true,
                    },
                    output: {
                        ecma: 5,
                        comments: false,
                        ascii_only: true,
                    },
                },
                parallel: true,
                cache: true,
                sourceMap: false,
            }),
            new OptimizeCSSAssetsPlugin({
                cssProcessorOptions: {
                    parser: safePostCssParser,
                    map: false
                },
            }),
        ],
        splitChunks: {
            chunks: "all",
            cacheGroups: {
                commons: {
                    chunks: "initial",
                    minChunks: 2,
                    maxInitialRequests: 5, // The default limit is too small to showcase the effect
                    minSize: 0 // This is example is too small to create commons chunks
                },
                'vendor-pageB': {
                    test: /react|react-router-dom|react-dom|prop-types|antd|@ant-design\/icons/, // 直接使用 test 来做路径匹配
                    chunks: "initial",
                    name: "vendor-pageB",
                    enforce: true,
                },
            }
        },
        runtimeChunk: true,
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js", ".jsx"],
    },
    plugins: [
        new SizePlugin(),
        // new BundleAnalyzerPlugin(),
        new LoadablePlugin(),
        new MiniCssExtractPlugin({
            // 抽离的样式叫什么名字（会生成在 css 文件夹下）`
            filename: "static/css/[name].css",
            // chunkFilename 是异步加载的 CSS 资源名 id 默认从数字 0 开始
            chunkFilename: "static/css/[id].css",
        }),
    ],
};
